#!/usr/bin/env python
# -*- encoding: utf-8 -*-
'''
@Date:2022/07/18 15:02:28
'''
import json
import datetime
import decimal

from flask import Flask as New_flask
from flask.json import JSONEncoder as _JSONEncoder
from flask_cors import CORS
from sqlalchemy.ext.declarative import DeclarativeMeta


#继承JSONEncoder处理sqlalchemy对象编码转换类
class JSONEncoder(_JSONEncoder):
    def default(self, obj):
        # if isinstance(obj, decimal.Decimal):
        #     return str(obj)
        # elif isinstance(obj, datetime.datetime):
        #     return obj.isoformat()
        # elif isinstance(obj, datetime.date):
        #     return obj.isoformat()
        if isinstance(obj, decimal.Decimal):
            return str(obj)
        elif isinstance(obj, (datetime.datetime, datetime.date)):
            return obj.isoformat()
        if isinstance(obj.__class__, DeclarativeMeta):
            #SQLAlchemy类
            fields = {}
            for field in [x for x in dir(obj) if not x.startswith('_') and x != 'metadata']:
                data = obj.__getattribute__(field)
                try:
                    json.dumps(data)  # 序列化对象
                    fields[field] = data
                    if data is None:
                        fields[field] = ''
                except TypeError:    # 添加了对datetime的处理
                    # if isinstance(data, datetime.datetime):
                    #     fields[field] = data.isoformat()
                    # elif isinstance(data, datetime.date):
                    #     fields[field] = data.isoformat()
                    if isinstance(data, (datetime.datetime, datetime.date)):
                        fields[field] = data.isoformat()
                    elif isinstance(data, datetime.timedelta):
                        fields[field] = (
                            datetime.datetime.min + data).time().isoformat()
                    elif isinstance(data, decimal.Decimal):
                        fields[field] = float(data)
                    else:
                        fields[field] = None
            # Json编码字典
            return fields

        return json.JSONEncoder.default(self, obj)



class Flask(New_flask):
    json_encoder = JSONEncoder

def register_blueprints(app: New_flask):
    """
    """
    from apps.home.views import home_router
    from apps.drug.views import drug_router
    from apps.drug_template.views import tmp_router
    from apps.user.views import user_router
    from apps.report.views import report_router
    from apps.client.views import client_router
    from apps.power.views import power_router
    from apps.monitor.views import monitor_router
    from apps.drug_form.views import drug_form_router
    from apps.stock_record.views import stock_router

    # 主概览相关
    app.register_blueprint(home_router, url_prefix="/api/home")
    # 试剂相关
    app.register_blueprint(drug_router, url_prefix="/api/drug")
    # 模板相关
    app.register_blueprint(tmp_router, url_prefix="/api/drug_tmplate")
    # 报表相关
    app.register_blueprint(report_router, url_prefix="/api/report")
    # 用户相关
    app.register_blueprint(user_router, url_prefix="/api/user")
    # 客户端相关
    app.register_blueprint(client_router, url_prefix="/api/client")

    # 获取用户权限
    app.register_blueprint(power_router, url_prefix="/api/power")
    
    # 获取温湿度监控
    app.register_blueprint(monitor_router, url_prefix="/api/monitor")

    # 获取自定义表单
    app.register_blueprint(drug_form_router, url_prefix="/api/drug_form")
    
    # 库存盘点相关
    app.register_blueprint(stock_router, url_prefix="/api/stock")

def create_app():
    app = Flask(__name__)
    CORS(app, supports_credentials=True)
    # app.config.from_object('setting')
    app.config["SECRET_KEY"] = "wYdilHT~TRw7j{lF+Ee5MR3nFBINONPUcObwjwzge&/(~[C?Yz"
    register_blueprints(app)
    return app


